package com.bstek.demo.esasyules;

import com.bstek.frame.model.ApiResult;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.support.composite.ActivationRuleGroup;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 测试类
 */
@Controller
@RequestMapping("rest/test")
public class EasyRuleController {

    @ResponseBody
    @RequestMapping(value = "/easyRule",method = RequestMethod.POST)
    public ApiResult<?> easyRule(@RequestBody  Person person) {
        Assert.notNull(person,"输入参数person不能为空值");

        RulesEngine adultEngine = new DefaultRulesEngine();
        Rules rules = new Rules();
        //rules.register(new MaleRule());
        // rules.register(new FemaleRule());

        /**
        * Easy Rules自带三种CompositeRule实现：
        * UnitRuleGroup : 单元规则组, 判断条件是与(AND)，符合所有条件执行全部，否则都不执行
        * ActivationRuleGroup : 激活式规则组，判断条件是亦或(XOR)触发第一个使用的规则，然后忽略其他的规则。组内的规则按自然排序(默认的优先级)
        * ConditionalRuleGroup : 条件规则组，如果具有最高优先级的规则计算结果为true，则触发其余规则
         */
        ActivationRuleGroup ruleGroup = new ActivationRuleGroup("myRuleGroup", "性别判断规则集");
        ruleGroup.addRule(new FemaleRule());
        ruleGroup.addRule(new MaleRule());
        rules.register(ruleGroup);

        System.out.println(person.toString());
        Facts facts = new Facts();
        facts.put("person", person);

        adultEngine.fire(rules, facts);

        return ApiResult.success(facts);
    }

    /**
     * 奇偶规则判断
     * @param num 输入整娄数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/easyRule2")
    public ApiResult<?> easyRule2(int num) {
        Assert.notNull(num, "输入参数num不能为空值");

        Rules rules = new Rules();
        rules.register(new EvenNumberRule());//注册偶数规则实现

        System.out.println(num);
        Facts facts = new Facts();
        facts.put("num", num);
        facts.put("result", "我是奇数");//给个默认值
        RulesEngine adultEngine = new DefaultRulesEngine();
        adultEngine.fire(rules, facts);

        return ApiResult.success(facts);
    }
}
